<template>
  <div v-if="addr.length === 0"
    class="w-48 h-36 ml-[200px] text-center leading-[150px] text-rose-400 hover:text-rose-500">
    <button class="hover:underline" @click="this.$router.push({ path: '/address' })">新增收货地址</button>
  </div>
  <div v-else>
    <div class="my-5 mx-14 flex flex-warp">
      <template v-for="(i, index) in addr" :key="index">
        <Addr class="mx-8 mt-2" :item="i" :aindex="index" @click="getArr(index)" :class="[{ get: idx == index }]"></Addr>
      </template>
    </div>
    <div class="text-center text-rose-400 hover:text-rose-500 mb-3">
      <button class="hover:underline" @click="this.$router.push({ path: '/address' })">管理收货地址</button>
    </div>
  </div>
  <v-table class="w-[1200px] mx-auto">
    <thead>
      <tr>
        <th class="text-left w-[500px]"> 商品 </th>
        <th class="text-left w-[300px]"> 规格 </th>
        <th class="text-center w-[100px]"> 单价 </th>
        <th class="text-center w-[100px]"> 数量 </th>
        <th class="text-center w-[100px]"> 实付 </th>
      </tr>
    </thead>
    <tbody>
      <tr v-for="i in Arr">
        <td>
          <img class="my-5 w-24 h-24 inline-block" :src="`http://127.0.0.1:8081${i.productImage}`" alt="加载失败">
          <div class="w-[300px] h-24 inline-block ml-3 font-base">{{ controlTitle(i.productName) }}</div>
        </td>
        <td>{{ i.spec }}</td>
        <td class="text-center">{{ i.sellPrice }}</td>
        <td class="text-center">{{ i.quantity }}</td>
        <td class="text-center">{{ allPrice(i) }}</td>
      </tr>
    </tbody>
  </v-table>
  <div class="my-3 mx-auto w-[1200px] text-xl font-bold text-right">
    <p> 总价: <span class="text-3xl font-bold text-red">￥{{ totalPrice }}</span></p>
    <p v-if="addr.length === 0">
      <button @click="this.$router.push({ path: '/address' })"
        class="text-rose-400 hover:text-rose-500 hover:underline">新增收货地址</button>
    </p>
    <div v-else class="text-zinc-400 text-lg font-thin">
      <p class="py-3 text-xl text-rose-200 border-b-2 font-normal border-solid border-rose-200">收货地址</p>
      <p class="py-1">{{ addr[idx].consignee }}</p>
      <p class="pb-1">{{ addr[idx].phone }}</p>
      <p class="pb-1">{{ addr[idx].address }}</p>
    </div>
    <button class='my-3 w-24 h-10 border-2 border-solid border-rose-500 rounded-xl hover:bg-rose-500 hover:text-white'
      @click="pay">支付</button>
  </div>
</template>

<script>
import Addr from '../../../components/user/Addr.vue'
import axios from 'axios'
export default {
  data() {
    return {
      Arr: [],
      totalPrice: 0,
      idx: '0',
      abc: [],
      addr: [],
      orderItemList: [],
      orderItem: {
        id: '',
        orderId: '',
        productId: '',
        amount: '',
        productName: '',
        specName: '',
        price: '',
        status: '',
        createTime: '',
        sendTime: '',
        receiptTime: '',
      }
    }
  },
  components: {
    Addr
  },
  mounted() {
    this.getData()
    this.getAdd()
    // this.getOrderItemList( this.Arr )
  },
  methods: {
    getData() {
      this.Arr = JSON.parse( this.$route.query.row )
      this.totalPrice = this.$route.query.totalPrice
    },
    //计算实付款
    allPrice( item ) {
      let price = parseFloat( item.sellPrice ) * parseInt( item.quantity )
      return price
    },
    //标题截取
    controlTitle( str ) {
      if ( str.length > 45 ) {
        str = str.slice( 0, 45 ) + '...'
      }
      return str
    },
    //计算总价
    allPrice2( arr ) {
      let sum = 0
      for ( let i = 0; i < arr.length; i++ ) {
        sum += this.allPrice( arr[ i ] )
      }
      return sum
    },
    //动态选中地址
    getArr( i ) {
      this.idx = i
    },
    // 获取地址列表
    getAdd() {
      axios( {
        url: 'http://127.0.0.1:8081/api/selectAddressByUserId',
        method: 'post',
        params: {
          token: window.localStorage.getItem( "userToken" ),
          userName: window.localStorage.getItem( "userName" ),
        }
      } ).then( res => {
        if ( res.data.success === false ) {        // 没有卡片；卡片过期；卡片伪造时
          window.localStorage.removeItem( "userToken" )     // 删除卡片，跳转到登录页面
          this.$router.push( { path: '/login' } )
        } else {
          this.addr = res.data.data.addressList
        }
      } )
    },
    // 支付成功提交订单
    pay() {
      const params = new URLSearchParams();
      params.append( 'token', window.localStorage.getItem( "userToken" ) )
      params.append( 'userName', window.localStorage.getItem( "userName" ) )
      params.append( 'address', this.addr[ this.idx ].address )
      params.append( 'consignee', this.addr[ this.idx ].consignee )
      params.append( 'phone', this.addr[ this.idx ].phone )
      params.append( 'payment', this.totalPrice )
      axios.post( "http://127.0.0.1:8081/api/insertOrder", params ).then( res => {
        for ( var i = 0; i < this.Arr.length; i++ ) {
          const params = new URLSearchParams();
          params.append( 'token', window.localStorage.getItem( "userToken" ) )
          params.append( 'orderId', res.data.data.orderId )
          params.append( 'productId', this.Arr[ i ].productId )
          params.append( 'amount', this.Arr[ i ].quantity )
          params.append( 'productName', this.Arr[ i ].productName )
          params.append( 'specName', this.Arr[ i ].spec )
          params.append( 'price', this.Arr[ i ].sellPrice )
          axios.post( "http://127.0.0.1:8081/api/insertOrderItem", params ).then( res => {
            if ( res.data.success === false ) {        // 没有卡片；卡片过期；卡片伪造时
              window.localStorage.removeItem( "userToken" )     // 删除卡片，跳转到登录页面
              this.$router.push( { path: '/login' } )
            } else {
              console.log( this.orderItemList[ i ] + '  ' + res.data.message )
            }
          } )
          this.$router.push( { path: '/paid' } )
        }
      } )
    },
    // 生成订单详情数组
    // getOrderItemList( Arr ) {
    //   for ( let index = 0; index < Arr.length; index++ ) {
    //     const element = Arr[ index ]
    //     this.orderItem.productId = element.productId
    //     this.orderItem.amount = element.quantity
    //     this.orderItem.productName = element.productName
    //     this.orderItem.specName = element.spec
    //     this.orderItem.price = element.sellPrice
    //     this.orderItemList.push( this.orderItem )
    //     console.log( this.orderItemList )
    //   }
    // },
  },
}
</script>

<style scoped></style>